package service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import model.ImageModel;
import entity.NewsImage;

public class ImageService {
	private ImageModel imgModel = new ImageModel();
	private InputStream in = null;
	private FileOutputStream fileOut = null;
	private OutputStream out = null;
	private NewsImage img = null;

	public void getImageFromUrl(String imgURL) {
		try {
			img = imgModel.findByURL(imgURL);
			if (img.isOk()) {
				// make folder in webapp if it's not exits : root folder, folder
				// by year, by month, by day.
				File superFolder = new File("../webapps/images_news");
				superFolder.mkdir();
				File yearFolder = new File(superFolder, img.getYear());
				yearFolder.mkdir();
				File monthFolder = new File(yearFolder, img.getMonth());
				monthFolder.mkdir();
				File dayFolder = new File(monthFolder, img.getDay());
				dayFolder.mkdir();

				// make image.
				File myImg = new File(dayFolder, img.getName());
				if (!myImg.exists()) {
					myImg.createNewFile();
				}

				// get image from url and write to file.
				URL url = new URL(img.getUrl());
				in = url.openStream();
				fileOut = new FileOutputStream(myImg);
				out = new BufferedOutputStream(fileOut);
				for (int b; (b = in.read()) != -1;) {
					out.write(b);
				}
				System.out.println("Download image complete !");
			}
		} catch (IOException ex) {

		} finally {
			imgModel.delete(img);
			try {
				// close all in, out stream.
				out.flush();
				out.close();
				fileOut.flush();
				fileOut.close();
				in.close();
			} catch (IOException ex) {

			}
		}
	}
}
